package com.app.config;

import com.alibaba.fastjson.JSON;
import com.app.entity.User;
import com.app.util.JwtUtil;
import com.app.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义springsecurity用户密码验证操作
 */
@Slf4j
public class jwtLoginFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager;
    private JwtUtil jwtUtil;


    public jwtLoginFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {
        this.authenticationManager = authenticationManager;
        this.jwtUtil = jwtUtil;
    }

    //登陆效验   访问/login路径就会被拦截到这里
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse res) {
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                request.getParameter("username"),
                request.getParameter("password")
        ));
    }


    @Override
    public void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) {
        User user = (User) auth.getPrincipal(); //拿到我们登陆用户
        String token = jwtUtil.createJWT("user", JSON.toJSONString(user));
        ResponseUtil.sendMessage(res, 200, "登陆成功", token);
    }

    //登陆失败
    @Override
    public void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ResponseUtil.sendMessage(response, 500, "账号或者密码错误", null);
    }
}
